import json
import os
import dashscope

# 从环境变量中获取 DASHSCOPE_API_KEY
api_key = os.environ.get('DASHSCOPE_API_KEY')
dashscope.api_key = api_key

def sentiment_analysis_with_function_call(text):
    """
    使用Function Call进行情感分析
    """
    # 定义情感分析函数
    functions = [
        {
            "name": "analyze_sentiment",
            "description": "分析文本的情感倾向",
            "parameters": {
                "type": "object",
                "properties": {
                    "sentiment": {
                        "type": "string",
                        "enum": ["positive", "negative", "neutral"],
                        "description": "情感分类"
                    },
                    "confidence": {
                        "type": "number",
                        "description": "置信度，0-1之间",
                        "minimum": 0,
                        "maximum": 1
                    },
                    "key_phrases": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "关键情感短语"
                    },
                    "intensity": {
                        "type": "string",
                        "enum": ["weak", "medium", "strong"],
                        "description": "情感强度"
                    }
                },
                "required": ["sentiment", "confidence"]
            }
        }
    ]

    messages = [
        {
            "role": "system",
            "content": "你是一个专业的情感分析助手。请分析用户文本的情感倾向，并调用函数返回结构化结果。"
        },
        {
            "role": "user",
            "content": f"请分析以下文本的情感：{text}"
        }
    ]

    try:
        response = dashscope.Generation.call(
            model='deepseek-v3',
            messages=messages,
            functions=functions,
            result_format='message'
        )

        if response.status_code == 200:
            return parse_function_call_response(response, text)
        else:
            return {
                "success": False,
                "error": f"API调用失败: {response.code} - {response.message}",
                "original_text": text
            }

    except Exception as e:
        return {
            "success": False,
            "error": f"发生错误: {str(e)}",
            "original_text": text
        }


def parse_function_call_response(response, original_text):
    """
    解析包含Function Call的响应
    """
    result = {
        "success": True,
        "original_text": original_text,
        "analysis": {}
    }

    if (hasattr(response, 'output') and
            hasattr(response.output, 'choices') and
            len(response.output.choices) > 0):

        choice = response.output.choices[0]
        if hasattr(choice, 'message'):
            message = choice.message

            # 检查是否有函数调用
            if hasattr(message, 'tool_calls') and message.tool_calls:
                function_call = message.tool_calls[0]
                try:
                    # 解析函数参数
                    arguments = json.loads(function_call['function'].get('arguments'))
                    result["analysis"] = arguments
                    result["function_name"] = function_call['function'].get('name')

                    # 添加情感中文映射
                    sentiment_map = {
                        "positive": "积极",
                        "negative": "消极",
                        "neutral": "中性"
                    }
                    intensity_map = {
                        "weak": "弱",
                        "medium": "中等",
                        "strong": "强"
                    }

                    result["analysis"]["sentiment_cn"] = sentiment_map.get(
                        arguments.get("sentiment"), "未知"
                    )
                    result["analysis"]["intensity_cn"] = intensity_map.get(
                        arguments.get("intensity", "medium"), "中等"
                    )

                except json.JSONDecodeError as e:
                    result["success"] = False
                    result["error"] = f"解析函数参数失败: {e}"

            # 如果没有函数调用，使用普通回复
            elif hasattr(message, 'content') and message.content:
                result["analysis"] = {
                    "direct_response": message.content,
                    "sentiment": "未知",
                    "sentiment_cn": "未知"
                }
            else:
                result["success"] = False
                result["error"] = "无有效响应"
    else:
        result["success"] = False
        result["error"] = "响应格式异常"

    return result

def batch_sentiment_analysis(texts):
    """
    批量情感分析
    """
    results = []
    for i, text in enumerate(texts, 1):
        print(f"分析第 {i}/{len(texts)} 条文本...")
        result = sentiment_analysis_with_function_call(text)
        results.append(result)
    return results

def print_analysis_results(results):
    """
    打印分析结果
    """
    print("\n" + "=" * 50)
    print("情感分析结果")
    print("=" * 50)

    for i, result in enumerate(results, 1):
        print(f"\n--- 结果 {i} ---")
        print(f"原文: {result['original_text']}")

        if not result.get("success", False):
            print(f"❌ 分析失败: {result.get('error', '未知错误')}")
            continue

        analysis = result.get("analysis", {})

        if "direct_response" in analysis:
            print(f"💬 模型回复: {analysis['direct_response']}")
        else:
            sentiment = analysis.get("sentiment_cn", "未知")
            confidence = analysis.get("confidence", 0)
            intensity = analysis.get("intensity_cn", "中等")
            key_phrases = analysis.get("key_phrases", [])

            # 情感图标
            sentiment_icons = {
                "积极": "😊",
                "消极": "😞",
                "中性": "😐"
            }

            icon = sentiment_icons.get(sentiment, "❓")

            print(f"{icon} 情感: {sentiment}")
            print(f"📊 置信度: {confidence:.2f}")
            print(f"⚡ 强度: {intensity}")

            if key_phrases:
                print(f"🔑 关键短语: {', '.join(key_phrases)}")

def generate_summary_report(results):
    """
    生成总结报告
    """
    successful_results = [r for r in results if r.get("success", False)]

    if not successful_results:
        print("没有成功的分析结果可生成报告")
        return

    sentiment_count = {}
    total_confidence = 0
    total_results = len(successful_results)

    for result in successful_results:
        analysis = result.get("analysis", {})
        sentiment = analysis.get("sentiment_cn", "未知")
        confidence = analysis.get("confidence", 0)

        sentiment_count[sentiment] = sentiment_count.get(sentiment, 0) + 1
        total_confidence += confidence

    print("\n" + "=" * 50)
    print("分析报告总结")
    print("=" * 50)
    print(f"📈 总分析数: {len(results)}")
    print(f"✅ 成功分析: {total_results}")
    print(f"📊 平均置信度: {total_confidence / total_results:.2f}" if total_results > 0 else "N/A")
    print("\n情感分布:")
    for sentiment, count in sentiment_count.items():
        percentage = (count / total_results) * 100
        print(f"  {sentiment}: {count} ({percentage:.1f}%)")

# 测试代码
def main():
    # 测试文本
    test_texts = [
        "这个产品真的太棒了，质量非常好，使用体验极佳！",
        "服务态度极差，等了很久都没人理，非常失望。",
        "今天天气不错，温度适中，适合外出。",
        "物流速度很快，包装也很仔细，但是产品本身有点小瑕疵。",
        "这是我用过最差的产品，完全不值这个价格！要求退货！"
    ]

    print("开始情感分析...")
    results = batch_sentiment_analysis(test_texts)

    # 打印详细结果
    print_analysis_results(results)

    # 生成总结报告
    generate_summary_report(results)

if __name__ == "__main__":
    main()